//
//  ByViewCitySelect.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/17.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByViewCitySelect.h"
@implementation ByModelCity
@end

@implementation ByViewCitySelect
{
    // data
    NSMutableArray *_provinces;
    NSMutableArray *_citys;
    NSMutableArray *_areas;
    
    NSInteger _provinceRow;
    NSInteger _cityRow;
    NSInteger _areaRow;
    
    // ui
    UIView *_toolBar;
    UIPickerView *_picker;
    
}

#pragma mark - init
- (instancetype)init {
    
    if (self = [super init]) {
        
        [self fetchInitDataFromDB];
        [self setupUI];
    }
    return self;
}
//- (void)safeAreaInsetsDidChange {
//
//    [super safeAreaInsetsDidChange];
//
//    if (@available(ios 11.0,*)) {
//        self.height = SCREEN_HEIGHT - self.safeAreaInsets.bottom;
//    }
//}

#pragma mark - 数据库取出城市数据
// 获取初始化的数据
- (void)fetchInitDataFromDB {
    
    _provinces = [NSMutableArray new];
    _citys = [NSMutableArray new];
    _areas = [NSMutableArray new];
    
    // 省份
    [_provinces addObjectsFromArray:[ByCoreAddressSqlite3 getAllProvinceModel]];
    
    // 城市-默认选中第一个省份，获取城市
    ByCoreProvinceModel *province = [_provinces firstObject];
    [_citys addObjectsFromArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
    
    // 区域-默认选中第一个城市，获取区域
    ByCoreCityModel *city = [_citys firstObject];
    [_areas addObjectsFromArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
}
// 获取城市数据
- (void)fetchCityData:(NSInteger )row{
    
    // 当前省份
    ByCoreProvinceModel *province = _provinces[row];
    [_citys removeAllObjects];
    [_citys setArray:[ByCoreAddressSqlite3 getAllCityModelWithProvinceID:province.provinceID]];
}
// 获取区域数据
- (void)fetchAreaData:(NSInteger )row{
    
    // 如果没有城市，那么地区也对应没有
    if (_citys.count == 0) {
        [_areas removeAllObjects];
        return;
    }
    // 当前城市
    ByCoreCityModel *city = _citys[row];
    [_areas removeAllObjects];
    [_areas setArray:[ByCoreAddressSqlite3 getAllAreaModelWithCityID:city.cityID]];
}

#pragma mark - 全局方法
- (void)show {
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = delegate.window;
    [window addSubview:self];

    if (@available(ios 11.0,*)) {
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - window.safeAreaInsets.bottom);
    } else {
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
    _toolBar.top = self.height;
    _picker.top = _toolBar.bottom;

    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
        _picker.bottom = self.height;
        _toolBar.bottom = _picker.top;
    }];
}
- (void)hide {
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        _toolBar.top = self.height;
        _picker.top = _toolBar.bottom;
    } completion:^(BOOL finished) {
        if (finished) {
            [self removeFromSuperview];
        }
    }];
}

#pragma mark - 创建视图
- (void)setupUI {
    
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    [self addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    
    _toolBar = [[UIView alloc] init];
    _toolBar.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self addSubview:_toolBar];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = FONT(14);
    [button setTitle:@"完成" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [_toolBar addSubview:button];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    [_toolBar addSubview:line];
    
    _picker = [[UIPickerView alloc] init];
    _picker.backgroundColor = [UIColor whiteColor];
    _picker.delegate = self;
    _picker.dataSource = self;
    [self addSubview:_picker];
    
    _toolBar.frame = CGRectMake(0, 0, SCREEN_WIDTH, 40);
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(60, 40));
        make.right.equalTo(_toolBar);
        make.centerY.equalTo(_toolBar);
    }];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(_toolBar);
        make.height.equalTo(@1);
        make.left.equalTo(@0);
        make.top.equalTo(@0);
    }];
    
    _picker.frame = CGRectMake(0, 0, SCREEN_WIDTH, 216);
}



#pragma mark - pickView delegate,datasource
// 列数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

// 行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return _provinces.count;
    } else if (component == 1) {
        return _citys.count;
    } else {
        return _areas.count;
    }
}

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    NSString *text;
    
    if (component == 0) {
        ByCoreProvinceModel *province = _provinces[row];
        text = province.province;
        
    } else if (component == 1) {
        ByCoreCityModel *city = _citys[row];
        text = city.city;
        
    } else {
        ByCoreAreaModel *area = _areas[row];
        text = area.area;
    }
    
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:text];
    [attr addAttribute:NSFontAttributeName value:FONT(14) range:NSMakeRange(0, 1)];
    return attr.copy;
}

// 选中单元格
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    if (component == 0) {
        
        _provinceRow = row;
        
        [self fetchCityData:row];    // 根据选择的省份重新获取城市数组
        [self fetchAreaData:0];      // 城市数组为当前城市数组中第一个城市的地区数组
        
        _provinceRow = row;
        _cityRow = 0;
        _areaRow = 0;
        
    } else if (component == 1) {
        
        _cityRow = row;
        
        [self fetchAreaData:row];    // 根据选择的城市重新获取地区数组
        
        _areaRow = 0;
        
        
    } else {
        
        _areaRow = row;
    }
    
    // 刷新picker
    [pickerView reloadAllComponents];
    [pickerView selectRow:_provinceRow inComponent:0 animated:YES];
    [pickerView selectRow:_cityRow inComponent:1 animated:YES];
    [pickerView selectRow:_areaRow inComponent:2 animated:YES];
    
    
    // 每次点击都获取当前的地址
    ByModelCity *model = [self buildCityModel];
    // 把当前地址回传到控制器里，设置UI
    if (self.didSelectCity) {
        self.didSelectCity(model);
    }
}


#pragma mark - 辅助
// 创建城市model
- (ByModelCity *)buildCityModel {
    
    ByModelCity *model = [[ByModelCity alloc] init];
    
    // 省
    ByCoreProvinceModel *province = _provinces[_provinceRow];
    model.province = province.province;
    model.provinceid = province.provinceID;
    
    // 市
    if (_citys.count == 0) { // 某省份下没有市了
        model.city = @"";
        model.cityid  =  @"0";
    } else {
        ByCoreCityModel *city = _citys[_cityRow];
        model.city = city.city;
        model.cityid = city.cityID;
    }
    
    // 地区
    if (_areas.count == 0) { // 某市中没有地区了
        model.area = @"";
        model.areaid = @"0";
    } else {
        ByCoreAreaModel *area = _areas[_areaRow];
        model.areaid = area.areaID;
        model.area = area.area;
    }
    
    model.fullAddress =[NSString stringWithFormat:@"%@%@%@", model.province, model.city, model.area];
    
    return model;
}

@end
